﻿using Core.Shop.EF;
using Core.Shop.Tool;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Core.Shop.Api
{
    [Route("api/[Controller]")]
    public class BaseController : ControllerBase
    {
        /// <summary>
        /// 数据库上下文
        /// </summary>
        public BaseDbContext Db
        {
            get
            {
                var serviceProvidersFeature = HttpContext.Features.Get<IServiceProvidersFeature>();
                var services = serviceProvidersFeature.RequestServices;
                var service = (BaseDbContext)services.GetService(typeof(BaseDbContext));
                return service;
            }
        }
        /// <summary>
        /// 数据库上下文
        /// </summary>
        public RedisHelper Redis
        {
            get
            {
                var serviceProvidersFeature = HttpContext.Features.Get<IServiceProvidersFeature>();
                var services = serviceProvidersFeature.RequestServices;
                var service = (RedisHelper)services.GetService(typeof(RedisHelper));
                return service;
            }
        }

        public int UserId
        {
            get 
            {
                var userIdStr = Redis.GetStringKey("Token:" + HttpContext.Request.Headers["Ike-Token"].ToString());
                if (userIdStr.HasValue)
                {
                    return int.Parse(userIdStr);
                }
                throw new Exception("Token已过期，请重新登录");
            }
        }

    }
}
